
#include <cstring>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>

#include "words.h"
#include "loader.h"

using namespace std;

static vector<Word> GlobalWords;

void WordMaster::GenerateOrder() {
    // Shuffle

    for (int i = 0; i < N_WORDS; ++i) {
        __Order.push_back(i);
    }

    random_shuffle(__Order.begin(), __Order.end());
}

Word WordMaster::GetWord() {
    if (__OrderIndex >= N_WORDS) {
        random_shuffle(__Order.begin(), __Order.end());
        __OrderIndex = 0;
        return GlobalWords[__Order[__OrderIndex]];
    }

    return GlobalWords[__Order[__OrderIndex++]];
}

vector<Word>& WordMaster::GetGlobalWords() {
    return GlobalWords;
}

void WordMaster::InitWords(const char *path = "words.txt") {
    WordFileLoader::LoadFrom(path, GlobalWords);
}

WordMaster::WordMaster(): __OrderIndex(0) {
    srand(time(0));
    GenerateOrder();
}

void FillWithTestWords() {
    FreeAllWords(GlobalWords);

    Word testWords[] = {
        {"Klee", "klee"},
        {"Diona", "diona"},
        {"Nahida", "nahida"},
        {"Qiqi", "qiqi"},
        {"Dori", "dori"},
        {"Sayo", "sayo"},
    };

    for (int i = 0; i < sizeof(testWords) / sizeof(Word); ++i) {
        char *tp = new char[50], *dp = new char[100];

        strcpy(tp, testWords[i].text);
        strcpy(dp, testWords[i].describe);

        GlobalWords.push_back(Word{tp, dp});
    }
}

void FreeAllWords(vector<Word> &words) {
    for (Word wd: words) {
        delete [] wd.text;
        delete [] wd.describe;
    }
}
